package com.myway.utils;

import java.util.StringTokenizer;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

public class FlightNoUtils {

	private static final Logger log = Logger.getLogger(FlightNoUtils.class);
	
	private FlightNoUtils() {
	}

	/**
	 * split flight no "HU7890" and returns "HU".
	 * 
	 * @param flightNo
	 * @return carrier code
	 */
	public final static String getCarrierCode(String flightNo) {
		Assert.notNull(flightNo, "flight no must not be null");
		if (flightNo.length() > 2) {
			return flightNo.substring(0, 2);
		}
		return null;
	}

	/**
	 * split flight no "EU7890" and returns "7890"
	 * 
	 * @param flightNo
	 * @return flight No
	 */
	public final static String getFlightNo(String flightNo) {
		Assert.notNull(flightNo, "Flight no must not be null");
		if (flightNo.length() > 2) {
			return flightNo.substring(2);
		}
		return null;
	}

	/**
	 * Match the flight number against the given pattern.
	 * 
	 * @param pattern
	 *            pattern for matching. Could be in any of the following formats: "JD", "JD*", "JD5157/5158"
	 * @param flightNo
	 *            flight number to be matched against the pattern.
	 * @return
	 */
	public final static boolean isMatched(String pattern, String flightNo) {
		return isMatched(pattern, flightNo, true);
	}
	
	/**
	 * Match the flight number against the given pattern.
	 * 
	 * @param pattern
	 *            pattern for matching. Could be in any of the following formats: "JD", "JD*", "JD5157/5158"
	 * @param flightNo
	 *            flight number to be matched against the pattern.
	 * @param ignoreCase
	 *            ignore alphabet case if set to true.
	 * @return
	 */
	public final static boolean isMatched(String pattern, String flightNo, boolean ignoreCase) {
		Assert.isTrue(StringUtils.hasText(pattern));
		Assert.isTrue(StringUtils.hasText(flightNo) && flightNo.trim().length() >= 4, "Invalid flight number");

		if (ignoreCase) {
			flightNo = flightNo.toUpperCase();
			pattern = pattern.toUpperCase();
		}
		
		log.debug("Matching " + flightNo + " against pattern " + pattern);
		StringTokenizer tokenizer = new StringTokenizer(pattern, "/");
		while (tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken();
			token = "*" + token + "*"; // wild-card match
			if (PatternMatchUtils.simpleMatch(token, flightNo)) {
				log.debug("Flight number " + flightNo + " is matched with " + token);
				return true;
			}
		}
		
		return false;
	}
}
